package ps.train.image;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.Parser;

import ps.train.image.Flickr;



import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	
	private GridView grid;
	private ImageView frame_image;	
	private TextView View_nsid, view_farm, view_server, view_photoID, view_secret, view_link; 
	private String api_key = Flickr.api;
	private String secrect = Flickr.secret;
	private String username = Flickr.username;
	private String noJsoncall = Flickr.noJsoncall;
	private String name_input ;
	private String link_user_id = "http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=";
	private String link_photo_id = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=";
	private String[] link_image;
	private String format = Flickr.format;	
	private String user_id;
	private String[] photo_id;
	private String[] farm_id;
	private String[] server_id;
	private String original="_o";
	private String size_z ="_z";
	private String[] secret_id;
	private int perpage = 1;
	private int page = 1;
	private String show_user_info;
	private String queryResult;
	private DownLoadSynTask downTask;
	private Flickr fr;
	private ProgressDialog pd;
	private Bitmap[] bitmap;
	private int total;
	private String[] URL ;
	private String[] largeURL;
	private Intent img;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_input_name);
        

        view_link = (TextView)findViewById(R.id.view_link_image);
       
       grid = (GridView)findViewById(R.id.gridview);
       
        LoadImage();
        
        grid.setOnItemClickListener(new OnItemClickListener() {
            
			public void onItemClick(AdapterView<?> view, View parent, int position,
					long id) {
				
				if(position>=0 && position<URL.length)
				{	
					Flickr.photoid = Flickr.photoIDs[position];
					Flickr.nextImage = 0;
					Flickr.pos = position;					
					Flickr.url = largeURL[position].toString();					
					img = new Intent(getApplicationContext(), ViewEachImage.class);
					startActivity(img);
					//finsh();
				}
			}
        });

                
    }
    
    public void  LoadImage() 
    {
    	
    	
    	name_input = fr.user_name;
		queryResult = getHttpUserId(name_input);
		
		
		show_user_info = getJSonUserId(queryResult);					
		//View_nsid.setText(show_user_info);
		
		user_id = getHttpPhotoId(show_user_info);
		
		getJSonPhotoFarm(user_id);
		//view_farm.setText(farm_id);
			
		getJSonServerid(user_id);
		//view_server.setText(server_id);
			
		getJSonPhotoID(user_id);
		//view_photoID.setText(photo_id);							
			
		getJSonSecret(user_id);
		//view_secret.setText(secret_id);
			 
    	
    	if(downTask != null) 
    	{
    		AsyncTask.Status diStatus = downTask.getStatus();
    	
    		if(diStatus != AsyncTask.Status.FINISHED)
    		{
    			return;
    		}
    	}
	    	downTask = new DownLoadSynTask(this);	    	
	    	link_image = new String[total];	    	
	    	URL = new String[total];
	    	largeURL = new String[total];
	    	Flickr.allUrl = new String[total];
	    	for(int i=0;i<total;i++)
	    	{
	    		link_image[i] = "http://farm"+farm_id[i]+".static.flickr.com/"+server_id[i]+"/"+photo_id[i]+"_"+secret_id[i]+".jpg";
	    		largeURL[i] = "http://farm"+farm_id[i]+".static.flickr.com/"+server_id[i]+"/"+photo_id[i]+"_"+secret_id[i]+size_z+".jpg";
	    		Flickr.allUrl[i] = URL[i] = link_image[i];	    		
	    	}	    	
	    	
	    		downTask.execute(URL);
	    	
    }
    

    
    public String getHttpUserId(String put)
    {
    	
    	link_user_id += api_key+username+put+format+noJsoncall;
    	StringBuilder builder = new StringBuilder();
    	String line;
    	String result ="";
    	
    	HttpParams params = new BasicHttpParams();
    	HttpConnectionParams.setSoTimeout(params, 5000);
    	HttpConnectionParams.setSoTimeout(params, 5000);
    	HttpClient client = new DefaultHttpClient(params);
    
    	HttpGet httpGet = new HttpGet(link_user_id);
    	
    	try {
			HttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream content = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
			
			while((line=reader.readLine())!=null)
			{
				builder.append(line + "\n");
			}
				content.close();
				result = builder.toString();
				
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
			return result;
    }
    
    public String getHttpPhotoId(String userID)
    {
    	
    	link_photo_id += api_key+"&user_id="+userID+format+noJsoncall;
    	StringBuilder builder = new StringBuilder();
    	String line;
    	String result ="";
    	
    	HttpParams params = new BasicHttpParams();
    	HttpConnectionParams.setSoTimeout(params, 5000);
    	HttpConnectionParams.setSoTimeout(params, 5000);
    	HttpClient client = new DefaultHttpClient(params);
    
    	HttpGet httpGet = new HttpGet(link_photo_id);
    	
    	try {
			HttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream content = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
			
			while((line=reader.readLine())!=null)
			{
				builder.append(line + "\n");
			}
				content.close();
				result = builder.toString();
				
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
			return result;
    }
    
    
    public  String getJSonUserId(String readJson)
    {
    	
    	 String jResult = null;
    	 String nsid = null;
    	 String id = null;
    	 String name_id = null;
    	 String stat = null;
    	
		try {
			//json = new JSONObject(test);
			JSONObject json = new JSONObject(readJson);
			JSONObject userObject = json.getJSONObject("user");
			
			id = userObject.getString("id");
			nsid = userObject.getString("nsid");				
			
			
			JSONObject userName = userObject.getJSONObject("username");
			name_id = userName.getString("_content");
			
			
			stat = json.getString("stat");
			
			jResult = id;
			
			System.out.print("getJSonUserId");
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   	
		return jResult;
    
    }
    
    public String[] getJSonPhotoID(String userID)
    {

    	int  Total ;
    	String[] ID_photo ;

    	
    	try {
			JSONObject json = new JSONObject(userID);
			JSONObject photos = json.getJSONObject("photos");
						
			Total = photos.getInt("total");
			total = Total;
			ID_photo = new String[total];
			photo_id = new String[total];
			Flickr.photoIDs = new String[total];
			
			JSONArray photo = photos.getJSONArray("photo");
			
			
			for(int i=0; i<photo.length(); i++)
			{
				
				JSONObject photo_i = photo.getJSONObject(i);	
				ID_photo[i] = photo_i.getString("id");
				
				Flickr.photoIDs[i] = photo_id[i] = ID_photo[i] ;
				System.out.print("getJSonPhotoID");
				
			}
			/*
			JSONObject photo_i = photo.getJSONObject(21);	
			ID_photo = photo_i.getString("id");
			*/			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return photo_id;
    }
    
    
    public String[] getJSonPhotoFarm(String userID)
    {

    	int  Total ;
    	
    	String[] Farm_id ;
    	String Stat = null;

    	
    	try {
			JSONObject json = new JSONObject(userID);
			JSONObject photos = json.getJSONObject("photos");
						
			Total = photos.getInt("total");
			total = Total;
			Farm_id = new String[total];
			farm_id = new String[total];
			
			JSONArray photo = photos.getJSONArray("photo");
			
			
			for(int i=0; i<photo.length(); i++)
			{
				
				JSONObject photo_i = photo.getJSONObject(i);				
				Farm_id[i] = photo_i.getString("farm");
				farm_id[i] = Farm_id[i] ;
				System.out.print("getJSonPhotoFarm");
			}
			/*
			JSONObject photo_i = photo.getJSONObject(21);	
			Farm_id = photo_i.getString("farm");
			jResult = Farm_id ;
			*/
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return farm_id;
    }
    

    public String[] getJSonServerid(String userID)
    {
    	String[] server_Id ;    	
    	int Total;
    	
    	JSONObject json;
		try {
			json = new JSONObject(userID);
			JSONObject photos = json.getJSONObject("photos");
			Total = photos.getInt("total");
			total = Total;
			server_Id = new String[total];
			server_id = new String[total];
			
			JSONArray photo = photos.getJSONArray("photo");
			for(int i=0; i<photo.length(); i++)
			{
				
				JSONObject photo_i = photo.getJSONObject(i);				
				server_Id[i] = photo_i.getString("server");
				server_id[i] = server_Id[i];
				System.out.print("getJSonServerid");
			}
			/*
			JSONObject photo_i = photo.getJSONObject(21);
			server_Id = photo_i.getString("server");
			jResult = server_Id;
			*/
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	return server_id;
    }

    
    public String[] getJSonSecret(String UserID)
    {
    	String[] secret ;
    	int Total;
    	
    	JSONObject json;
		try {
			json = new JSONObject(UserID);
			JSONObject photos = json.getJSONObject("photos");
			Total = photos.getInt("total");
			total = Total;
			secret = new String[total];
			secret_id = new String[total];
			
			JSONArray photo = photos.getJSONArray("photo");
			for(int i=0; i<photo.length(); i++)
			{				
				JSONObject photo_i = photo.getJSONObject(i);				
				secret[i] = photo_i.getString("secret");
				secret_id[i] = secret[i];
				System.out.print("getJSonSecret");
			}
			/*
			JSONObject photo_i = photo.getJSONObject(21);
			secret = photo_i.getString("secret");
			jResult = secret;
			*/
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    	return secret_id;
    }
    
    
    public  class DownLoadSynTask extends AsyncTask<String, Bitmap, Bitmap[] >
    {
    	private Context mContext;
    	
    	public DownLoadSynTask(Context con)
    	{ 
    		this.mContext = con;
    	}
    	
    	

		@Override
		protected void onProgressUpdate(Bitmap[] photos) {
			// TODO Auto-generated method stub
			grid.setAdapter(new ImageAdapter(mContext, bitmap));
		}



		protected void onPreExecute() {
			
			pd = showLoading();

    	}

		
		protected void onPostExecute(Bitmap[] result) 
    	{
			
		    	if(result !=null)
		    	{
		    		grid.setAdapter(new ImageAdapter(mContext));
		    	}
			
	    	pd.dismiss();
    	}
    	

		@Override
		protected Bitmap[] doInBackground(String[] urls) 
		{					
			bitmap = new Bitmap[total];
			for(int i=0;i<urls.length;i++)
			{
				Flickr.pics[i] = bitmap[i] = downloadImage(urls[i]);
				publishProgress(bitmap);
			}
			 return bitmap;				
		}
		
		private Bitmap downloadImage(String url)
    	{		
			
			HttpClient client = new DefaultHttpClient();			
    	    HttpGet getRequest ;
    	    Bitmap image = null ;
			//for(int i=0;i<url.length;i++)	
			//{
		    	    try {
		    	    	getRequest = new HttpGet(url);
		    	        HttpResponse response = client.execute(getRequest);		    	       
		    			
		    	        HttpEntity entity = response.getEntity();
		    	        if (entity != null)
		    	        {
		    	        	InputStream inputStream = entity.getContent();
		    	           	
		    	        	 BitmapFactory.Options opt = new BitmapFactory.Options();		    	       
		    	        	 opt.inSampleSize = 6; // original size		    	        	
		    	        	 if (image == null )
		    	        	   try {
		    	        	     // just a sample, not only just decode file
		    	        		   image  = BitmapFactory.decodeStream(inputStream, null, opt);
		    	        	   } catch (OutOfMemoryError e) {
		    	        	     // Here is just a sample, we can use many another option to decrease bitmap size 
		    	        	     opt.inSampleSize++;
		    	        	   }

		    	            		//image  = BitmapFactory.decodeStream(inputStream);		    	            		

		    	                	Log.d("downloadImage","download image :");
		    	                	return image;
		    	        }
		    	    } catch (Exception e)
		    	    {
		    	        // Could provide a more explicit error message for IOException or IllegalStateException
		    	       e.printStackTrace();   	       
		    	    }
		    	    
	    		
	    	//}
				return null;
		
    	}
		
    }
    
    public ProgressDialog showLoading()
    {
    	ProgressDialog p = ProgressDialog.show(this,"Loading" ,"..........");
    	p.setCancelable(true);
    	
    	return p;
    }
    

    public class ImageAdapter extends BaseAdapter{

    	Context con;
    	ImageView Iview;
    	
    	public ImageAdapter(Context mcon)
    	{
    		   this.con = mcon;
    	}
    	
    	public ImageAdapter(Context mcon , Bitmap[] bmp)
    	{
    		this.con = mcon;
    		bitmap = bmp;
    	}
    	
    	
		public int getCount() {
			// TODO Auto-generated method stub
			return total;
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stubi
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			ImageView v; 
			
			 if (convertView == null) {  // if it's not recycled, initialize some attributes
		            v = new ImageView(con);
		            v.setLayoutParams(new GridView.LayoutParams(85, 85));
		            v.setScaleType(ImageView.ScaleType.CENTER_CROP);
		            v.setPadding(8, 8, 8, 8);
		        } else {
		            v = (ImageView) convertView;
		        }
			
			 	v.setImageBitmap(bitmap[position]);
			 	
			return v;
		}
    	
    }
    
}